let Promise = require('bluebird');
let request = Promise.promisify(require('request'));
const superagent = require('superagent');

function Wechat(opts) {
    let that = this;
    this.appID = opts.appID;
    this.appSecret = opts.appsecret;
    this.getAccessToken = opts.getAccessToken;
    this.saveAccessToken = opts.saveAccessToken;
    this.getAccessToken().then((data) => {
        try {
            data = JSON.parse(data);
        } catch (error) {
            return that.updateAccessToken()
        }
        if (that.isValidAcessToken(data)) {
            return Promise.resolve(data);
        } else {
            return that.updateAccessToken();
        }
    }).then((res) => {
        that.access_token = res.access_token;
        that.expires_in = res.expires_in;
        that.saveAccessToken(res);
    })
}
Wechat.prototype.isValidAcessToken = function (data) {
    if (!data || !data.access_token || !data.expires_in) {
        return false;
    }
    let expires_in = data.expires_in;
    let now = Date.now();
    if (now < expires_in) {
        return true;
    } else {
        return false;
    }
};
Wechat.prototype.updateAccessToken = function () {
    let appID = this.appID;
    let appSecret = this.appSecret;
    let url = `https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${appID}&secret=${appSecret}`;
    return new Promise((resolve, reject) => {
        request({
            url,
            json: true
        }).then(function (res) {
            let data = res.body;
            let now = Date.now();
            let ticketUrl = `https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=${data.access_token}&type=jsapi`;
            superagent.get(ticketUrl).then(result => {
                let expires_in = now + (result.body.expires_in - 20) * 1000;
                data.expires_in = expires_in;
                data.ticket = result.body.ticket;
                resolve(data)
            })
        })
    })
}
module.exports = Wechat;